<template>
  <div ref="swiperRef" class="swiper">
    <!-- 轮播图容器 -->
    <div class="swiper-wrapper">
      <!-- 图片存放处 -->
      <div v-for="pic in imageList" :key="pic.id" class="swiper-slide">
        <img :src="pic.imgUrl" alt="banner" />
      </div>
    </div>
    <!-- 分页器 -->
    <div class="swiper-pagination"></div>

    <!-- 左右翻页箭头 -->
    <div class="swiper-button-prev"></div>
    <div class="swiper-button-next"></div>
  </div>
</template>

<script>
import Swiper, { Navigation, Pagination, Autoplay } from "swiper";

import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/pagination";
export default {
  name: "MyCarousel",
  props: {
    imageList: Array,
  },
  // 监视
  watch: {
    imageList: {
      handler(imageList) {
        // 将首页轮播图的立即监视效果去掉
        if (!imageList.length) return;
        // 将new Swiper的任务加入到微队列中，等待页面更新完成之后，再执行
        this.$nextTick(() => {
          // 此时发现只new了一次
          new Swiper(this.$refs.swiperRef, {
            modules: [Navigation, Pagination, Autoplay],
            loop: true,

            // 分页器
            pagination: {
              el: ".swiper-pagination",
              clickable: true,
            },

            // 左右翻页箭头
            navigation: {
              nextEl: ".swiper-button-next",
              prevEl: ".swiper-button-prev",
            },

            // 自动播放
            autoplay: {
              pauseOnMouseEnter: true,
              disableOnInteraction: false,
            },
          });
        });
      },
      // 开启深度监视
      immediate: true,
    },
  },
};
</script>

<style scoped></style>
